package com.lanou.zy.projecta.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.bigkoo.convenientbanner.ViewPagerScroller;
import com.bigkoo.convenientbanner.transforms.CubeOutTransformer;
import com.google.gson.Gson;
import com.lanou.zy.projecta.R;
import com.lanou.zy.projecta.activity.FindNextStepActivity;
import com.lanou.zy.projecta.activity.WebViewActivity;
import com.lanou.zy.projecta.adapter.RecommendRecyclerViewAdapter;
import com.lanou.zy.projecta.adapter.RecommendViewPagerAdapter;
import com.lanou.zy.projecta.database.DBHelper;
import com.lanou.zy.projecta.entity.Hot_Notes;
import com.lanou.zy.projecta.entity.TitleImage;
import com.lanou.zy.projecta.entity.TitleImageData;
import com.lanou.zy.projecta.greedao.entity.HotNotes;
import com.lanou.zy.projecta.greedao.entity.SlideResult;
import com.lanou.zy.projecta.greedao.entity.SubjectResult;
import com.lanou.zy.projecta.util.GetVolleyDatas;
import com.lanou.zy.projecta.util.OnItemClickListener;
import com.lanou.zy.projecta.util.ProgressView.CircleProgress;
import com.lanou.zy.projecta.util.SwipeRefreshLoadingLayout;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by dllo on 15/10/21.
 */
public class RecommendFragment extends Fragment implements View.OnClickListener, SwipeRefreshLoadingLayout.OnLoadListener {
    private ImageView fnsTop_Iv, fnsButtomLeft_Iv, fnsButtomRight_Iv;
    private TextView findNextStepAll_Tv;
    private ImageView[] img;
    private View view;
    private String str;
    private String[] webUrl = new String[3];
    private String[] webName = new String[3];
    private int count = 0;  // 下拉加载url后缀

    // 加载数据前的动画
    private CircleProgress mProgressView;
    private RelativeLayout recommend_Rv;

    private ViewPager recommendViewPager;
    private RecommendViewPagerAdapter recommendViewPagerAdapter;    // 轮播图

    private RecyclerView recyclerView;
    private RecommendRecyclerViewAdapter recommendRecyclerViewAdapter;
    private RequestQueue queue;
    private List<HotNotes> datas;
    private boolean flag = true; // 对话框是否弹出过

    private SwipeRefreshLoadingLayout swipeRefreshLoadingLayout; // 下拉刷新

    // 数据库
//    private SQLiteDatabase db;
    // 管理者
//    private DaoMaster mDaoMaster;
//    // 会话
//    private DaoSession mDaoSession;

    private DBHelper helper;
    private List<SubjectResult> sr;
    private List<SlideResult> st;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_recommend, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        setRunnable();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        loadRecyclerUrl();
        initViewPagerScroll();
        startTurning(4000);
    }

    private View initView() {
        swipeRefreshLoadingLayout = (SwipeRefreshLoadingLayout) view.findViewById(R.id.swipeRefreshLoadingLayout);
        swipeRefreshLoadingLayout.setOnLoadListener(this);
        fnsTop_Iv = (ImageView) view.findViewById(R.id.fnsTop_Iv);
        fnsTop_Iv.setOnClickListener(this);
        fnsButtomLeft_Iv = (ImageView) view.findViewById(R.id.fnsButtomLeft_Iv);
        fnsButtomLeft_Iv.setOnClickListener(this);
        fnsButtomRight_Iv = (ImageView) view.findViewById(R.id.fnsButtomRight_Iv);
        fnsButtomRight_Iv.setOnClickListener(this);
        img = new ImageView[]{fnsTop_Iv, fnsButtomLeft_Iv, fnsButtomRight_Iv};
        findNextStepAll_Tv = (TextView) view.findViewById(R.id.findNextStepAll_Tv);
        findNextStepAll_Tv.setShadowLayer(5F, 3F, 3F, R.color.colorF0F0F0);
        findNextStepAll_Tv.setOnClickListener(this);
        mProgressView = (CircleProgress) view.findViewById(R.id.mProgressView);
        recommend_Rv = (RelativeLayout) view.findViewById(R.id.recommend_Rv);

        recommendViewPager = (ViewPager) view.findViewById(R.id.recommendViewPager);
        recommendViewPagerAdapter = new RecommendViewPagerAdapter(getChildFragmentManager());
        recommendViewPager.setPageTransformer(true, new CubeOutTransformer());
        recommendViewPager.setAdapter(recommendViewPagerAdapter);

        recommendRecyclerViewAdapter = new RecommendRecyclerViewAdapter(getActivity());
        recyclerView = (RecyclerView) view.findViewById(R.id.recommendRecyclerView);

        helper = DBHelper.getInstance();
        RecyclerViewHeader header = (RecyclerViewHeader) view.findViewById(R.id.header);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(view.getContext(), 1);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(recommendRecyclerViewAdapter);
        recommendRecyclerViewAdapter.setOnItemClickLitener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", datas.get(position).getView_url());
                intent.putExtra("name", datas.get(position).getTitle());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        header.attachTo(recyclerView, true);
        mProgressView.startAnim();
        return view;
    }

    /**
     * 发现下一站的数据拉取
     */
    private void initData() {
        sr = helper.searchSubjectAll();
        Log.d("RecommendFragment", "sr:" + sr);
        st = helper.searchSlideAll();

        queue = Volley.newRequestQueue(getActivity());
        // 判断数据库是否为空  为空则从网络拉取
        if (sr != null || sr.size() > 0 || st != null || st.size() > 0) {
            recommendViewPagerAdapter.addData(st);


            String url = "http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883753&lon=121.544282&channel=360m";
            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    TitleImage ti = gson.fromJson(response, TitleImage.class);
                    TitleImageData td = ti.getData();
                    sr = td.getSubject();
                    st = td.getSlide();

                    // 发现下一站的三张图片
                    if (sr != null) {
                        helper.addSubject(sr);
                        int i = 0;
                        for (SubjectResult subjectResult : sr) {
                            str = subjectResult.getPhoto(); //得到需要的图片网址
                            webUrl[i] = subjectResult.getUrl();
                            webName[i] = subjectResult.getTitle();
                            GetVolleyDatas.getBitmapRequest(str, img[i]);
                            i++;
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
            queue.add(request);


        } else {
            String url = "http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883753&lon=121.544282&channel=360m";
            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    TitleImage ti = gson.fromJson(response, TitleImage.class);
                    TitleImageData td = ti.getData();
                    sr = td.getSubject();
                    st = td.getSlide();

                    // 发现下一站的三张图片
                    if (sr != null) {
                        helper.addSubject(sr);
                        int i = 0;
                        for (SubjectResult subjectResult : sr) {
                            str = subjectResult.getPhoto(); //得到需要的图片网址
                            webUrl[i] = subjectResult.getUrl();
                            webName[i] = subjectResult.getTitle();
                            GetVolleyDatas.getBitmapRequest(str, img[i]);
                            i++;
                        }
                    }
                    // 轮播图
                    recommendViewPagerAdapter.addData(st);
                    helper.addSlide(st);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
            queue.add(request);
        }

    }


    /**
     * 最下面recyclerview的数据拉取
     */
    private void loadRecyclerUrl() {

        datas = helper.searchHotNotesAll();
        if (datas != null && datas.size() > 0) {
            recommendRecyclerViewAdapter.addData(datas);
            recommend_Rv.setVisibility(View.GONE);
        } else {
            count += 10;
            String recyclerUrl = "http://open.qyer.com/qyer/recommands/trip?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883682&lon=121.544338&type=index&page=1&count=" + count + "";
            StringRequest request = new StringRequest(recyclerUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    swipeRefreshLoadingLayout.setLoading(false);
                    Gson gson = new Gson();
                    Hot_Notes hn = gson.fromJson(response, Hot_Notes.class);
                    if (hn != null) {
                        datas = hn.getData();
                        if (datas != null) {
                            recommendRecyclerViewAdapter.addData(datas);
                            mProgressView.stopAnim();
                            recommend_Rv.setVisibility(View.GONE);
                            if (flag) {
                                showAlertDialog();
                                flag = false;
                            }
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
            queue.add(request);
        }
    }

    private boolean turning;   // 是否在翻页
    private boolean canTurn = false; // 是否可以翻页
    private long autoTurningTime; // 翻页间隔时间
    private Handler handler = new Handler();
    private Runnable r;

    private void setRunnable() {
        if (r == null) {
            r = new Runnable() {
                @Override
                public void run() {
                    if (recommendViewPager != null) {
                        int page = recommendViewPager.getCurrentItem() + 1;
                        recommendViewPager.setCurrentItem(page);
                        handler.postDelayed(r, autoTurningTime);
                    }
                }
            };
        } else
            handler.postDelayed(r, autoTurningTime);
    }

    //     开始轮播
    public ViewPager startTurning(long autoTurningTime) {
        //如果是正在翻页的话先停掉
        if (turning) {
            stopTurning();
        }
        //设置可以翻页并开启翻页
        canTurn = true;
        this.autoTurningTime = autoTurningTime;
        turning = true;
        handler.postDelayed(r, autoTurningTime);
        return recommendViewPager;
    }


    /**
     * 停止轮播
     */
    public void stopTurning() {
        turning = false;
        handler.removeCallbacks(r);
    }

    /**
     * 设置ViewPager的滑动速度
     */
    private void initViewPagerScroll() {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            ViewPagerScroller scroller = new ViewPagerScroller(
                    recommendViewPager.getContext());
            mScroller.set(recommendViewPager, scroller);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发现下一站的按钮
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.findNextStepAll_Tv:
                Intent intent = new Intent(getActivity(), FindNextStepActivity.class);
                startActivity(intent);
                break;

            case R.id.fnsTop_Iv:
                Intent fnstIntent = new Intent(getActivity(), WebViewActivity.class);
                fnstIntent.putExtra("url", webUrl[0]);
                fnstIntent.putExtra("name", webName[0]);
                startActivity(fnstIntent);
                break;

            case R.id.fnsButtomLeft_Iv:
                Intent fnslIntent = new Intent(getActivity(), WebViewActivity.class);
                fnslIntent.putExtra("url", webUrl[1]);
                fnslIntent.putExtra("name", webName[1]);
                startActivity(fnslIntent);

                break;

            case R.id.fnsButtomRight_Iv:
                Intent fnsrIntent = new Intent(getActivity(), WebViewActivity.class);
                fnsrIntent.putExtra("url", webUrl[2]);
                fnsrIntent.putExtra("name", webName[2]);
                startActivity(fnsrIntent);
                break;
        }
    }

    /**
     * 下拉加载
     */
    @Override
    public void onLoad() {
        loadRecyclerUrl();
    }

    /**
     * 通知框
     */
    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle("Bug来袭"); // 标题文字
        builder.setIcon(R.mipmap.iconfont_tishi); // 标题边上的图标

        builder.setMessage("亲爱的用户，一大波Bug已经来袭，我的时间已经不多了，请抓紧时间使用");
        builder.setPositiveButton("我已知晓", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "祝你好运", Toast.LENGTH_SHORT).show();

            }
        });

        builder.setNegativeButton("吓着我了", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "别怕，我还能撑10分钟。。", Toast.LENGTH_SHORT).show();

            }
        });
        builder.show();

    }
}
